#! /usr/bin/env python

import os, sys, shutil
import urllib2
import flickrapi
import sqlite3

api_key     = 'e597cdeedb619f3f47ca999cd6f42149'
api_secret  = '578a2ab88db7e31b'

dbconn  = sqlite3.connect('flickrwatcher.db')
cursor  = dbconn.cursor()

cursor.execute('CREATE TABLE IF NOT EXISTS watch (username text, user_id text, photo_url text, dateupload integer, UNIQUE (username, user_id, photo_url) ON CONFLICT REPLACE)')

dbconn.commit()

username    = raw_input('Enter username: ')
if not os.path.exists(username):
    os.mkdir(username)

flickr          = flickrapi.FlickrAPI(api_key, api_secret)
(token, frob)   = flickr.getTokenPartOne(perms='read')

if not token:
    raw_input("Press ENTER after you authorized this program.")

flickr.getTokenPartTwo((token, frob))

user        = flickr.people_findByUsername(username=username)
user_id     = user.user[0]['nsid']
contacts    = flickr.contacts_getList(user_id=user_id)

for contact in contacts.contacts[0].contact:
    user_id     = contact['nsid']
    contactname = contact['username']

    if not os.path.exists(username+'/'+contactname):
        os.mkdir(username+'/'+contactname)

    lastdate = None
    cursor.execute('SELECT MAX(dateupload) FROM watch WHERE username=? AND user_id=?', (username, user_id))
    for row in cursor:
        lastdate = row[0]

    if lastdate:
        photos  = flickr.photos_search(user_id=user_id, min_upload_date=lastdate, safe_search='3', extras='date_upload', per_page=10)
    else:
        photos  = flickr.photos_search(user_id=user_id, safe_search='3', extras='date_upload', per_page=10)

    if photos.photos[0]['pages'] == '0':
        continue

    for photo in photos.photos[0].photo:
        photo_url = 'http://farm%(farm)s.static.flickr.com/%(server)s/%(id)s_%(secret)s.jpg' % photo
        fname = '%(farm)s_%(server)s_%(id)s_%(secret)s.jpg' % photo

        cursor.execute('SELECT * FROM watch WHERE user_id=? AND photo_url=?', (user_id, photo_url))

        downloaded = False
        for row in cursor:
            downloaded = True
            break

        if not downloaded:
            photod  = urllib2.urlopen(photo_url)
            fd      = open(username+'/'+contactname+'/'+fname, 'w')
            shutil.copyfileobj(photod, fd)
            photod.close()
            fd.close()
            cursor.execute('INSERT INTO watch (username, user_id, photo_url, dateupload) VALUES (?, ?, ?, ?)', (username, user_id, photo_url, photo['dateupload']))
            dbconn.commit()

dbconn.close()
